package net.lulihu.pangolin.headless.common.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 协议消息编码器 extends LengthFieldBasedFrameDecoder
 */
public class ProtocolMessageEncoder extends MessageToByteEncoder<ProtocolMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, ProtocolMessage msg, ByteBuf out) {
        int bodyLen = 1;

        byte[] body = msg.getBody();
        if (body != null) bodyLen += body.length;

        // 写入总包长度
        out.writeInt(bodyLen);

        // 写入类型数据
        out.writeByte(msg.getType());
        // 写入主体数据
        if (body != null) out.writeBytes(body);
    }

}
